﻿using MediatR;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Infrstructre.Interface;
using RBAC_Uthorization.Read.API.Application.Command.RoleMenuCommand;
using RBAC_Uthorization.Read.API.DTO;

namespace RBAC_Uthorization.Read.API.Application.CommandHandlers.RoleMenuHandler
{
    public class RoleMenuFIndIdCommandHandlers : IRequestHandler<RoleMenuFIndIdCommand, ApiResult<List<string>>>
    {
        private readonly IRoleMenuFuncRepository _roleMenuFuncRepository;
        private readonly IRoleMenuRepository _roleMenuRepository;
        private readonly ILogger<RoleMenuFIndIdCommandHandlers> _logger;

        public RoleMenuFIndIdCommandHandlers(ILogger<RoleMenuFIndIdCommandHandlers> logger, IRoleMenuRepository roleMenuRepository, IRoleMenuFuncRepository roleMenuFuncRepository)
        {
            _logger = logger;
            _roleMenuRepository = roleMenuRepository;
            _roleMenuFuncRepository = roleMenuFuncRepository;
        }

        public async Task<ApiResult<List<string>>> Handle(RoleMenuFIndIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var userIds = new HashSet<string>();
                var roleMenulist = await _roleMenuRepository.GetAllAsunc(x=>x.role_id==request.RoleId&&x.del_flag==0);
                if (roleMenulist != null)
                {
                    foreach (var item in roleMenulist)
                    {
                        userIds.Add(item.menu_id.ToString());
                    }
                   
                }
                var rolemenufunlist = await _roleMenuFuncRepository.GetAllAsunc(x => x.role_id == request.RoleId && x.del_flag == 0);
                if(rolemenufunlist != null)
                {
                    foreach (var item in rolemenufunlist)
                    {
                        string s=(item.menu_id+"-"+item.fun_id);
                        userIds.Add(s);
                    }
                }
                return new ApiResult<List<string>>() { Data= userIds.ToList() };


            }
            catch (Exception ex)
            {
                _logger.LogError(ex,"角色菜单功能id反填异常");
                return new ApiResult<List<string>>() { Code = ResultCode.Fail, Message = "角色菜单功能异常" };
            }
        }
    }
}
